<template>
  <div id="BigFileUpload">
    <el-upload
      class="upload-demo"
      action="https://jsonplaceholder.typicode.com/posts/"
      :on-change="handleChange"
      :file-list="fileList"
      :http-request="fileUpload"
    >
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
  </div>
</template>

<script>
export default {
  name: "BigFileUpload",
  data() {
    return {
      fileList: [{name: "food.jpeg",url: "" }]
    };
  },
  methods: {
    // 上传接口
    httpUpload(formData) {
      console.log("在这里模拟调接口:", formData);
      return {
        errCode: 0
      };
    },
    // 上传事件
    handleChange(file, fileList) {
      // console.log(file, fileList);
    },
    fileUpload(file) {
      console.log(file);
      const blob = file.file;
      // 文件大小
      const fileSize = blob.size;
      // 文件名
      const fileName = blob.name;

      console.log('fileSize=', fileSize);
      console.log('fileName=', fileName);

      // 定义每个切片的大小
      const sliceSize = 1 * 1024 * 1024;
      // 切片的总数
      const totalSlzie = Math.ceil(fileSize / sliceSize);
      console.log('totalSlzie=', totalSlzie);

      // 遍历切片
      for (let i = 0; i < totalSlzie; i++) {
        // 切片的开始与结束的标识
        let startIndex = i,
          endIndex = startIndex + sliceSize;
        // 每个切片的大小
        const chunk = blob.slice(startIndex, endIndex);
        // 使用FormData得到参数
        const formData = this.getFormDataParams(chunk, fileName, fileSize);
        // 请求分片上传接口
        const result =  this.httpUpload(formData);
      }
    },
    //每次分片的参数
    getFormDataParams(chunk, fileName, fileSize) {
      const formData = new FormData();
      formData.append("chunk", chunk);
      formData.append("fileName", fileName);
      formData.append("fileSize", fileSize);
      console.log('formData=', formData);
      return formData;
    }
  }
};
</script>
